<?PHP
  class Task{

    private $script        = "";
    private $interval      = 60;

    /**
     *
     * @return string
     */
    public function getScript(){
      return $this->script;
    }

    /**
     *
     * @param string $value 
     */
    public function setScript($value){
      $this->script = $value;
    }

    /**
     *
     * @return int 
     */
    public function getInterval(){
      return $this->interval;
    }

    /**
     *
     * @param int $value 
     */
    public function setInterval($value){
      $this->interval = $value;
    }

    /**
     *
     * @param string $value 
     */
    public function setLastExecution($value){
      $this->lastExecution = $value;
    }

    public function execute(){
      EventManager::RaiseEvent("before_executing_task", array("task" => $this));
      $script = DataBase::Current()->EscapeString($this->script);
      DataBase::Current()->Execute("UPDATE {'dbprefix'}tasks SET lastExecution = NOW() WHERE script = '".$script."'");
      include(Settings::getInstance()->get("root").$this->script);
      EventManager::RaiseEvent("after_executing_task", array("task" => $this));
    }

    /**
     *
     * @param int $limit
     * @return Task 
     */
    public static function getOverdued($limit = 1){
      $res = array();

      $limit = DataBase::Current()->EscapeString($limit);
      
      $tasks = DataBase::Current()->readRows("SELECT * FROM {'dbprefix'}tasks WHERE DATE_ADD(lastExecution, INTERVAL `interval` MINUTE) < NOW() or lastExecution IS NULL or DATE_ADD(lastExecution, INTERVAL `interval` MINUTE) IS NULL LIMIT 0,".$limit);
      foreach($tasks as $task){
        $newTask = new Task();
        $newTask->setScript($task->script);
        $newTask->setInterval($task->interval);
        $newTask->setLastExecution($task->lastExecution);
        $res[] = $newTask;
      }

      return $res;
    }

  }
?>